package org.micode.libs.smon.utils;

import org.micode.libs.smon.vo.CpuInfo;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.util.Util;

public class CpuUtils {

    /**
     * 采集数据等待的毫秒数
     */
    private static final int OSHI_WAIT_MS = 1000;

    private static final SystemInfo systemInfo = new SystemInfo();

    private static final HardwareAbstractionLayer hardware = systemInfo.getHardware();

    public static CpuInfo readCpu() {
        CpuInfo info = new CpuInfo();
        fillCpu(info);
        return info;
    }

    public static void fillCpu(CpuInfo info) {
        if (null == info) {
            return;
        }

        CentralProcessor processor = hardware.getProcessor();

        // CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();

        Util.sleep(OSHI_WAIT_MS);

        long[] ticks = processor.getSystemCpuLoadTicks();

        long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
        long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
        long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
        long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
        long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
        long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
        long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
        long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];

        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;

        info.setCoreCount(processor.getLogicalProcessorCount());
        info.setSystemUsage(cSys * 1.0 / totalCpu);
        info.setUserUsage(user * 1.0 / totalCpu);
        info.setIowaitUsage(iowait * 1.0 / totalCpu);
        info.setCurrentUsage(1.0 - (idle * 1.0 / totalCpu));
    }

    public static void main(String[] args) {
        CpuInfo cpu = readCpu();
        System.out.println("CPU核数量: " + cpu.getCoreCount() +
                ", 系统使用率: " + cpu.getSystemUsage() +
                ", 用户使用率: " + cpu.getUserUsage() +
                ", 当前等待率: " + cpu.getIowaitUsage() +
                ", 当前使用率: " + cpu.getCurrentUsage());
    }

}
